<?php
/**
 * Created by PhpStorm.
 * User: lvshuyun
 * Date: 2015/6/11
 * Time: 11:59
 */

namespace common\models\DAO;


use yii\db\ActiveRecord;

class AdminPower extends ActiveRecord {

    public function rules(){
        return [
            [['controller','action','roleID'],'required']
        ];
    }

    /**
     * 定义与角色表的关系
     * @return \yii\db\ActiveQuery
     */
    public function getRole(){
        return $this->hasOne(AdminRole::className(), ['id' => 'roleID']);
    }

    /**
     * 根据RoleID返回权限数据
     * @param int $role_id 角色ID
     * @return array
     */
    public function getByRole($role_id){
        $result = AdminPower::find()
            ->where([
                'roleID' => $role_id
            ])
            ->asArray()
            ->all();
            return $result;
    }

    /**
     * 检查权限
     * @param $role_id
     * @param $controller_id
     * @param $action_id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function checkPower($role_id, $controller_id, $action_id){
        $result = AdminPower::find()
            ->where([
                'roleID' => $role_id,
                'controller' => $controller_id,
                'action' => $action_id,
            ])
            ->asArray()
            ->all();
        return $result;
    }

    /*
     * 批量更新某个角色的权限
     */
    public function updatePowers($roleID, $powers){
        $roleID = intval($roleID);
        if($roleID>0 && !empty($powers) && is_array($powers)){
            $model = new AdminPower();
            //先全部删除再增加
            $model->deleteAll(['roleID'=>$roleID]);
            foreach($powers as $p){
                $model = new AdminPower();
                $model->roleID = $roleID;
                $model->controller = $p['controller'];
                $model->action = $p['action'];;
                $model->save();
            }
            return true;
        }
        return false;
    }

    /*
     * 删除某个Role的所有权限
     */
    public function delRolePower($id){
        return $this->deleteAll(['roleID'=>$id]);
    }

}